package com.atguigu.tingshu.order.handle;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Slf4j
@Component
public class RedisDelayHandle {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoService orderInfoService;

    @Scheduled(cron = "0/1 * * * * ?")
    public void listener() {

        // 使用分布式锁防止任务重复执行
        RLock rLock = redissonClient.getLock(RedisConstant.DELAY_PAY_LOCK);  // order-delay-lock
        boolean tryLock = rLock.tryLock();
        if(tryLock) {           // 获取到分布式锁以后执行关单业务逻辑代码

            // 获取阻塞队列
            RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque(KafkaConstant.QUEUE_ORDER_CANCEL);

            try {

                // 从阻塞队列中获取到订单Id
                String orderNo = blockingDeque.take();
                if(!StringUtils.isEmpty(orderNo)) {     // 订单Id 不为空的时候，调用取消订单方法
                    log.info("接收延时队列成功，订单id：{}", orderNo);
                    orderInfoService.orderCancel(orderNo);
                }

            } catch (InterruptedException e) {
                log.error("接收延时队列失败");
                e.printStackTrace();
            } finally {

                // 释放分布式锁
                rLock.unlock();
            }

        }

    }
}
